package com.gcloud.mesh.dcs.chain.ali;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.ecs20140526.models.CreateInstanceRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.dcs.dao.SchedulerStepDao;
import com.gcloud.mesh.dcs.entity.SchedulerStepEntity;
import com.gcloud.mesh.header.vo.dcs.ALiVMInstantInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.MyBusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

//@Component
@Slf4j
public class CreateInstance_6 extends AbstractAliMigrationStep {

    @Autowired
    private SchedulerStepDao schedulerStepDao;

    @Override
    public boolean checkStatus(String stepId) {
        SchedulerStepEntity stepEntity = schedulerStepDao.getById(stepId);
        JSONObject jsonObject = JSONObject.parseObject(stepEntity.getAttach());
        String regionId = jsonObject.getString("regionId");
        String accessKeyId = jsonObject.getString("accessKeyId");
        String accessSecret = jsonObject.getString("accessSecret");
        String dstInstanceId = jsonObject.getString("dstInstanceId");
        return isInstanceCreated(accessKeyId,accessSecret,regionId,dstInstanceId,maxCheckTime);
    }

    @Override
    public boolean isSyncChain() {
        return false;
    }

    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        String accessKeyId = jsonObject.getString("accessKeyId");
        String accessSecret = jsonObject.getString("accessSecret");
        String destRegionId = jsonObject.getString("regionId");
        String imageId = jsonObject.getString("imageId");
        ALiVMInstantInfoVO vo = JSONObject.toJavaObject(jsonObject.getJSONObject("srcInstanceInfo"),ALiVMInstantInfoVO.class);
        String instanceId = this.createInstance(accessKeyId,accessSecret,destRegionId,imageId,vo);
        jsonObject.put("dstInstanceId",instanceId);
        schedulerStepDao.updateAttachBySchedulerJobId(schedulerJobId,jsonObject.toString());
        filterChain.doExec(schedulerJobId,jsonObject.toString(),filterChain,stepChain);
    }


    @Override
    public String chainName(String attach) {
        return "创建实例";
    }

    @Override
    public int getOrder() {
        return 6;
    }

    public String createInstance(String accessKeyId, String accessKeySecret, String destRegionId, String imageId, ALiVMInstantInfoVO info){
        try {
            com.aliyun.ecs20140526.Client client =  createECSClient(accessKeyId,accessKeySecret,destRegionId);
            CreateInstanceRequest createInstanceRequest = new CreateInstanceRequest()
                    .setRegionId(destRegionId)
                    .setImageId(imageId)
                    .setInstanceType(info.getInstanceType())
                    .setInternetChargeType(info.getInternetChargeType())
                    .setInternetMaxBandwidthIn(info.getInternetMaxBandwidthIn())
                    .setInternetMaxBandwidthOut(info.getInternetMaxBandwidthOut())
                    .setPasswordInherit(true)
                    .setHostName(info.getHostName())
                    .setInstanceChargeType(info.getInstanceChargeType())
//                    .setPassword("gcloud123!@#")
                    ;
            return client.createInstance(createInstanceRequest).getBody().getInstanceId();
        } catch (Exception e) {
            log.error("创建实例失败",e);
            throw new MyBusinessException("创建实例失败"+e.getMessage());
        }
    }

    public boolean isInstanceCreated(String accessKeyId, String accessKeySecret,String regionId,String instanceId,Integer maxCheckTime){
        try {
            com.aliyun.ecs20140526.Client ecsClient = createECSClient(accessKeyId, accessKeySecret, regionId);
            DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
                    .setRegionId(regionId)
                    .setInstanceIds("[\""+instanceId+"\"]");
            DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance ii = ecsClient.describeInstances(describeInstancesRequest).getBody().getInstances().getInstance().get(0);
            return ii!=null;
        } catch (Exception e) {
            if(maxCheckTime!=null && maxCheckTime-->0){
                return isInstanceCreated(accessKeyId,accessKeySecret,regionId,instanceId,maxCheckTime);
            }
            return false;
        }
    }

}
